// 参考B站 React组件基础 ｜ 受控组件与非受控组件分析对比

import React from "react";

import MultiSelect from "@/components/ui/multi-select";

// 主要在三方面有区别：一、设置值；二、可编辑性；三、父组件取值

// 受控组件组件内的值随父组件的state变化，并且不能直接编辑，需要使用onChange函数将组件生成的新值接收后手动改state
// 非受控组件只通过defaultValue接收初始值，不随父组件的state变化，自身值可编辑，父组件要取它的值要么通过ref获取，要么查找元素获取
const ComponentControllDemo: React.FC = () => {
  const [num, setNum] = React.useState(10);
  const [selection, setSelection] = React.useState(["1", "3"]);
  const inputRef = React.useRef<HTMLInputElement>(null);

  return (
    <form className="flex flex-col">
      {/* 受控组件 */}
      <input
        type="number"
        value={num}
        onChange={(e) => {
          console.log(e);
          setNum(parseInt(e.target.value));
        }}
      />
      <br />
      {/* 非受控组件 */}
      <input type="number" ref={inputRef} defaultValue={num} />
      <br />
      <button type="button" onClick={() => setNum(num + 1)}>
        +1
      </button>
      <br />

      <MultiSelect
        options={[
          { label: "a", value: "1" },
          { label: "b", value: "2" },
          { label: "c", value: "3" },
          { label: "d", value: "4" },
          { label: "e", value: "5" },
        ]}
        selectedOptions={selection}
        onSelectionChange={(value) => {
          console.log(value);
          setSelection(value);
        }}
      />
      <button
        type="button"
        onClick={() => {
          console.log(num);
          console.log(inputRef.current);
          console.log(inputRef.current && inputRef.current.value);
        }}
      >
        print
      </button>
    </form>
  );
};

export default ComponentControllDemo;
